﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Threading;
using System.Threading.Tasks;

namespace PioneerBoilerplate.Repository.UnitOfWorks
{
    public class UnitOfWorkHandle<TDbContext> : IUnitOfWorkHandle<TDbContext> where TDbContext : DbContext
    {
        private readonly IServiceScope _serviceScope;

        public bool IsDisposed { get; private set; }

        public UnitOfWorkHandle(IServiceScope serviceScope)
        {
            _serviceScope = serviceScope;
        }

        public TDbContext GetActiveUnitOfWork()
        {
            return _serviceScope.ServiceProvider.GetRequiredService<TDbContext>();
        }

        public void Dispose()
        {
            _serviceScope.Dispose();
            IsDisposed = true;
            // 清空当前 Handle 或回到 OuterHandle
            AsyncLocalCurrentUnitOfWorkHandleProvider<TDbContext>.Current = null;

        }

        public int SaveChange()
        {
            var dbContext = GetActiveUnitOfWork();
            if (dbContext == null)
            {
                return 0;
            }
            return dbContext.SaveChanges();
        }

        public async Task<int> SaveChangeAsync()
        {
            var dbContext = GetActiveUnitOfWork();
            if (dbContext == null)
            {
                return await Task.FromResult(0);
            }
            return await dbContext.SaveChangesAsync(CancellationToken.None);
        }
    }
}
